#include "net.hpp"
#include <iostream>

using namespace jsonrpc;

// 处理RPC请求的回调函数
void handleRpcRequest(const BaseConnection::ptr& conn, BaseMessage::ptr& msg) {
    if (msg->getMessageType() != MType::REQ_RPC) {
        LOG_ERROR("Invalid message type for RPC request");
        return;
    }

    auto rpcReq = std::dynamic_pointer_cast<RpcRequest>(msg);
    if (!rpcReq) {
        LOG_ERROR("Failed to cast to RpcRequest");
        return;
    }

    LOG_INFO("Received RPC request: method=%s", rpcReq->getMethod().c_str());

    // 创建响应
    auto rsp = MessageFactory::create<jsonrpc::RpcResponse>();
    rsp->setRid(rpcReq->getRid());
    rsp->setMessageType(MType::RSP_RPC);
    
    // 简单处理请求
    if (rpcReq->getMethod() == "add") {
        Json::Value params = rpcReq->getParams();
        if (params.isMember("num1") && params.isMember("num2")) {
            int sum = params["num1"].asInt() + params["num2"].asInt();
            Json::Value result;
            result["sum"] = sum;
            rsp->setResult(result);
            rsp->setRCode(RCode::RCODE_OK);
        } else {
            rsp->setRCode(RCode::RCODE_INVALID_PARAMS);
        }
    } else {
        rsp->setRCode(RCode::RCODE_NOT_FOUND_SERVICE);
    }

    // 发送响应
    conn->send(rsp);
}

// 处理主题请求的回调函数
void handleTopicRequest(const BaseConnection::ptr& conn, BaseMessage::ptr& msg) {
    if (msg->getMessageType() != MType::REQ_TOPIC) {
        LOG_ERROR("Invalid message type for Topic request");
        return;
    }

    auto topicReq = std::dynamic_pointer_cast<TopicRequest>(msg);
    if (!topicReq) {
        LOG_ERROR("Failed to cast to TopicRequest");
        return;
    }

    LOG_INFO("Received Topic request: key=%s, optype=%d", 
             topicReq->getTopicKey().c_str(), 
             static_cast<int>(topicReq->getOptype()));

    // 创建响应
    auto rsp = MessageFactory::create<jsonrpc::TopicResponse>();
    rsp->setRid(topicReq->getRid());
    rsp->setMessageType(MType::RSP_TOPIC);
    rsp->setRCode(RCode::RCODE_OK);

    // 发送响应
    conn->send(rsp);
}

// 处理服务请求的回调函数
void handleServiceRequest(const BaseConnection::ptr& conn, BaseMessage::ptr& msg) {
    if (msg->getMessageType() != MType::REQ_SERVICE) {
        LOG_ERROR("Invalid message type for Service request");
        return;
    }

    auto serviceReq = std::dynamic_pointer_cast<ServiceRequest>(msg);
    if (!serviceReq) {
        LOG_ERROR("Failed to cast to ServiceRequest");
        return;
    }

    LOG_INFO("Received Service request: method=%s, optype=%d", 
             serviceReq->getMethod().c_str(), 
             static_cast<int>(serviceReq->getOptype()));

    // 创建响应
    auto rsp = MessageFactory::create<jsonrpc::ServiceResponse>();
    rsp->setRid(serviceReq->getRid());
    rsp->setMessageType(MType::RSP_SERVICE);
    rsp->setRCode(RCode::RCODE_OK);
    rsp->setOptype(serviceReq->getOptype());
    rsp->setMethod(serviceReq->getMethod());

    // 如果是服务发现请求，返回一些示例地址
    if (serviceReq->getOptype() == ServiceOptype::SERVICE_DISCOVERY) {
        std::vector<Address> addrs = {
            {"192.168.1.100", 8080},
            {"192.168.1.101", 8081}
        };
        rsp->setHost(addrs);
    }

    // 发送响应
    conn->send(rsp);
}

// 消息处理总函数
void onMessage(const BaseConnection::ptr& conn, BaseMessage::ptr& msg) {
    switch (msg->getMessageType()) {
        case MType::REQ_RPC:
            handleRpcRequest(conn, msg);
            break;
        case MType::REQ_TOPIC:
            handleTopicRequest(conn, msg);
            break;
        case MType::REQ_SERVICE:
            handleServiceRequest(conn, msg);
            break;
        default:
            LOG_ERROR("Unknown message type: %d", static_cast<int>(msg->getMessageType()));
            break;
    }
}

int main() {
    // 创建服务器
    auto server = ServerFactory::create(8888);
    
    // 设置消息回调
    server->setMessageCallback(onMessage);
    
    // 设置连接回调
    server->setConnectionCallback([](const BaseConnection::ptr& conn) {
        LOG_INFO("New connection established");
    });
    
    // 设置关闭回调
    server->setCloseCallback([](const BaseConnection::ptr& conn) {
        LOG_INFO("Connection closed");
    });
    
    // 启动服务器
    LOG_INFO("Starting server on port 8888...");
    server->start();
    
    return 0;
}